﻿using FastCloud.Base.Config;
using FastUtil.Log;
using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FastCloud.Base.Desgin
{
    [DisallowConcurrentExecution]
    public class CloudJob : IJob
    {
        public string TaskName { set; get; }
        public string TaskTag { set; get; }

        public CloudJob()
        {

        }

        public Task Execute(IJobExecutionContext context)
        {
            return Task.Factory.StartNew(() =>
            {
                TaskName = Convert.ToString(context.JobDetail.JobDataMap.Get("TaskName"));
                TaskTag = Convert.ToString(context.JobDetail.JobDataMap.Get("TaskTag"));
                LogUtil.WriteLog(CloudUtil.GetContentPath()+"/Logs/TaskScheduler", "log_", string.Format("开始执行任务，任务名称：{0}，任务标识：{1}！", TaskName, TaskTag));
                try
                {
                    ExecuteJob();
                }
                catch (Exception e)
                {
                    LogUtil.WriteLog(CloudUtil.GetContentPath() + "/Logs/TaskScheduler", "log_", string.Format("执行任务发生异常，任务名称：{0}，任务标识：{1}！", TaskName, TaskTag));
                    throw e;
                }
                LogUtil.WriteLog(CloudUtil.GetContentPath() + "/Logs/TaskScheduler", "log_", string.Format("结束执行任务，任务名称：{0}，任务标识：{1}！", TaskName, TaskTag));
            });
        }

        public void LogJob(string JobLogContent)
        {
            DirectoryInfo JobLogDir = new DirectoryInfo(CloudUtil.GetContentPath() + "/Logs/JobLog");
            if (!JobLogDir.Exists)
            {
                JobLogDir.Create();
            }
            DirectoryInfo JobExecuteLogDir = new DirectoryInfo(CloudUtil.GetContentPath() + "/Logs/JobLog/"+ TaskTag);
            if (!JobExecuteLogDir.Exists)
            {
                JobExecuteLogDir.Create();
            }
            LogUtil.WriteLog(CloudUtil.GetContentPath() + "/Logs/JobLog/" + TaskTag, "log_", JobLogContent);
        }

        public virtual void ExecuteJob()
        {

        }
    }
}
